from app.schemas.plot_defect import *
from utils.plot import PLOT

import cv2
import numpy as np
from urllib.request import urlopen
from loguru import logger
from utils.upload import oss_upload
from utils.request import Request

def plot(plot_defect: PlotDefect):
    resp = urlopen(plot_defect.file_url)
    plot_img = np.asarray(bytearray(resp.read()), dtype=np.uint8)
    plot_img = cv2.imdecode(plot_img, cv2.IMREAD_COLOR)

    boxes = []
    labels = []
    colors = []
    for defect_label in plot_defect.defect_label_list:
        pos = defect_label.position
        boxes.append([pos.x, pos.y, pos.x + pos.width, pos.y + pos.height])
        label_text = (defect_label.name + ' | ' if defect_label.name else '') + defect_label.create_staff_name
        labels.append(label_text)
        colors.append(PLOT.hex_to_rgb(defect_label.color))

    # 绘制所有标注框
    plot_img = PLOT.plot_box(image=plot_img,
                             boxes=boxes,
                             labels=labels,
                             colors=colors)
    _, buffer = cv2.imencode('.jpg', plot_img)
    image_bytes = buffer.tobytes()
    upload_plot_defect_image(image_bytes, plot_defect)


def upload_plot_defect_image(plot_img, plot_defect: PlotDefect):
    upload = oss_upload(plot_defect.oss_config)
    data = None
    res = upload(f'{plot_defect.id}.jpg', plot_img)
    if res:
        object_key = res
        data = {'id': plot_defect.id, 'objectKey': object_key}
        logger.info(f"[plot_defect_image]上传oss成功")
        Request.callback_result(data, url=plot_defect.upload_callback_url)